#include <iostream>
#include <vector>
#include <string>
using namespace std;

bool isDoubleFilpNum(long long target, int base) {
    vector<int> octDigits, newBaseDigits;
    long long tempTarget = target;
    while (target != 0) { octDigits.push_back(target % 10); target /= 10; }
    while (tempTarget != 0) { newBaseDigits.push_back(tempTarget % base); tempTarget /= base; }
    for (int i = 0; i < octDigits.size(); i++) {
        if (octDigits[i] != octDigits[octDigits.size() - 1 - i]) { return false; }
    }
    for (int j = 0; j < newBaseDigits.size(); j++) {
        if (newBaseDigits[j] != newBaseDigits[newBaseDigits.size() - 1 - j]) { return false; }
    }
    return true;
}

int main() {
    long long target; int base;
    cin >> target >> base;
    long long result = 0;
    for (long long i = 1; i < target; i++) {
        result += isDoubleFilpNum(i, base) ? i : 0;
    }
    cout << result;
    return 0;
}